import boto3
import traceback

import json
import datetime
client = boto3.client('events')

global_parameters = {
    "enableNotification": True,
    "source": "pt.spider",
    "detailType": "Spider State-change Notification",
    "metadata": {}
}


def processRequest(req, event=None, context=None):
    raise NotImplementedError("processRequest not implemented")


def handler(event, context):
    print("triggered by EventHandler...")
    print("event is %s" % event)

    try:
        if isinstance(event["detail"], str):
            eventDetail = json.loads(event["detail"])
        else:
            eventDetail = event["detail"]

        req = {
            "source": event["source"],
            "detailType": event["detail-type"],
            "metadata": eventDetail.get("metadata", {}),
            "payload": eventDetail.get("payload", {}),
            # "state": eventDetail.get("state", ""),
            # "result": eventDetail.get("result", ""),
        }
        respDict = processRequest(req, event, context)
        if respDict and not isinstance(respDict, dict):
            raise Exception("resp type must be dict, now is %s" % type(respDict))

        if global_parameters["enableNotification"]:
            entries = [{
                    "Source": global_parameters["source"],
                    "DetailType": global_parameters["detailType"],
                    "Detail": json.dumps({
                        "state": "COMPLETED",
                        "result": "SUCCESS",
                        "metadata": {**global_parameters.get("metadata", {}), **eventDetail.get("metadata", {})},
                        "payload": respDict
                    }),
                    "Resources": [],
                    "Time": datetime.datetime.now()
                }]
            print("putting success event to EventBus, event detail is %s..." % entries)
            response = client.put_events(
                Entries=entries
            )
            print("put success event to EventBus")
    except Exception as ex:
        traceback.print_exc()
        if global_parameters["enableNotification"]:
            entries = [{
                    "Source": global_parameters["source"],
                    "DetailType": global_parameters["detailType"],
                    "Detail": json.dumps({
                        "state": "COMPLETED",
                        "result": "ERROR",
                        "metadata": {**global_parameters.get("metadata", {}), **eventDetail.get("metadata", {})},
                        "payload": repr(ex)
                    }),
                    "Resources": [],
                    "Time": datetime.datetime.now()
                }]
            print("putting error event to EventBus, event detail is %s..." % entries)
            response = client.put_events(
                Entries=entries
            )
            print("put error event to EventBus")
